package com.yunduo.controller.front;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunduo.common.JwtUtils;
import com.yunduo.common.RetunData.CommonReturn;
import com.yunduo.common.RetunData.statuscode.impl.ResultCode;
import com.yunduo.common.RetunData.statuscode.impl.ServiceCode;
import com.yunduo.common.RetunData.statuscode.impl.UserCode;
import com.yunduo.common.YunDuoConst.ShopCarParam;
import com.yunduo.common.YunDuoUtils;
import com.yunduo.entity.Good;
import com.yunduo.entity.Shop;
import com.yunduo.entity.ShopGoods;
import com.yunduo.entity.User;
import com.yunduo.entity.front.ShopCar;
import com.yunduo.entity.front.ShopCarItem;
import com.yunduo.entity.front.vo.ShopCarData;
import com.yunduo.handler.exceptionhandler.OperationException;
import com.yunduo.service.GoodService;
import com.yunduo.service.ShopGoodsService;
import com.yunduo.service.ShopService;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 购物车控制类
 * 使用hash存储
 * redis_car
 *  - userid,carData
 *  - userid,carData
 *  //TO-DO 用户下线清空购物车
 */
@RestController
@RequestMapping("/shopcar")
public class ShopCarController {

    @Resource
    private GoodService goodService;
    @Resource
    private ShopService shopService;
    @Resource
    private ShopGoodsService shopGoodsService;
    @Resource
    private RedisTemplate redisTemplate;

    //加入购物车,为空就创建购物车
    @GetMapping("/add")
    public CommonReturn createShopCar(String id){
        User user = JwtUtils.getDataByJwtToken(YunDuoUtils.getRequest());
        if(user == null){
            throw new OperationException(UserCode.USER_IS_NOT_LOGIN);
        }
        HashOperations hashOperations = redisTemplate.opsForHash();
        ShopCar data = (ShopCar)hashOperations.get(ShopCarParam.SHOPCAR_REDIS, user.getId());
        //查出商店id
        ShopGoods shop = shopGoodsService.getOne(new LambdaQueryWrapper<ShopGoods>().eq(ShopGoods::getGoodId, id));
        if(shop== null){
            throw new OperationException(ServiceCode.PARAM_ERROR);
        }
        List<ShopCarItem> goods;
        if(data==null) {
            goods = new ArrayList<>();
        }else{
            goods = data.getGoods();
        }
        //反复点击加入购物车 更新商品
        for (int i = 0; i < goods.size(); i++) {
            ShopCarItem item = goods.get(i);
            boolean isExist = item.getGoodId().equals(shop.getGoodId());
            if(isExist){    //商品已经存在
                int count = item.getCount();
                item.setCount(count+1);
            }else{    //新商品
                goods.add(new ShopCarItem(shop.getGoodId(),shop.getShopId(),1));
            }
        }
        //第一次创建购物车
        if (goods.size() == 0) {
            goods.add(new ShopCarItem(shop.getGoodId(),shop.getShopId(),1));
        }
        ShopCar shopCar = new ShopCar();
        shopCar.setId(user.getId());
        shopCar.setGoods(goods);
        hashOperations.put(ShopCarParam.SHOPCAR_REDIS,user.getId(),shopCar);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //拉取用户购物车
    @GetMapping("/get")
    public CommonReturn getShopCar(){
        User user = JwtUtils.getDataByJwtToken(YunDuoUtils.getRequest());
        if(user == null){
            throw new OperationException(UserCode.USER_IS_NOT_LOGIN);
        }
        HashOperations hashOperations = redisTemplate.opsForHash();
        ShopCar car = (ShopCar)hashOperations.get(ShopCarParam.SHOPCAR_REDIS, user.getId());
        if(car == null){
            return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",new ArrayList<>());
        }
        List<ShopCarItem> goods = car.getGoods();
        List<ShopCarData> data = new ArrayList<>();
        Iterator<ShopCarItem> iterator = goods.iterator();
        while (iterator.hasNext()){
            ShopCarItem item = iterator.next();
            Good good = goodService.getById(item.getGoodId());
            Shop shop = shopService.getById(item.getShopId());
            data.add(new ShopCarData(good,shop,item.getCount()));
        }
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",data);
    }

    //修改购物车中数据
    @PostMapping("/update")
    public CommonReturn updateShopCar(@RequestBody ShopCar shopCar){
        User user = JwtUtils.getDataByJwtToken(YunDuoUtils.getRequest());
        if(user == null){
            throw new OperationException(UserCode.USER_IS_NOT_LOGIN);
        }
        if(shopCar.getGoods() == null){
            throw new OperationException(ResultCode.UNDEFINE);
        }
        shopCar.setId(user.getId());
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.put(ShopCarParam.SHOPCAR_REDIS,user.getId(),shopCar);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //清空购物车
    @GetMapping("/delete")
    public CommonReturn deleteShopCar(){
        User user = JwtUtils.getDataByJwtToken(YunDuoUtils.getRequest());
        if(user == null){
            throw new OperationException(UserCode.USER_IS_NOT_LOGIN);
        }
        HashOperations hashOperations = redisTemplate.opsForHash();
        hashOperations.delete(ShopCarParam.SHOPCAR_REDIS,user.getId());
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }
}
